import storys from '@/models/storys';
import projects from '@/models/projects';
import storyWithproject from '@/models/storyWithproject';
import { reviewStatus, checkStatus as checkStatusMap } from '@/utils/data';
import { isEmpty } from '@/utils/tools';
import { ddSendOnlineStoryMsg, sendMsgMergeDone } from '@/services/dingtalk/func';
import { addLogs } from '@/services/logs';
import { analysisToken } from '@/utils/Auth/auth';
import dayjs from 'dayjs';
import { ObjectId } from 'mongodb';
import { syncStorySearch } from '../tapd/index';

dayjs.locale('zh-cn');

const weekday = require('dayjs/plugin/weekday');

dayjs.extend(weekday);

// import { tapd2types } from '@/utils/data';

// const convertKey = (arr) => {
//   const newArr: any = [];
//   for (let i = 0; i < arr.length; i += 1) {
//     const obj = {};
//     Object.keys(arr[i]).forEach((item) => {
//       if (tapd2types[item]) {
//         obj[tapd2types[item]] = arr[i][item];
//       }
//     });
//     newArr.push(obj);
//   }
//   return newArr;
// };

// 查询今日上线的需求
export const syncGetList = async (params: { online_time?: string }) => {
  const { online_time } = params;
  // const reuslt = await storys.unionFind({ online_time });
  // return convertKey(reuslt);
  // 今日上线的需求
  const s = await storys.getList(params, undefined, 1, 100);
  // 获取今日上线的需求id
  const ids = s.map((item) => item.id).filter(Boolean);
  // 查一下需求关联项目的表里的
  // 有online_time的是合并分支
  let res = await storyWithproject.getList({ $or: [{ id: { $in: ids } }, { online_time }] }, undefined, 1, 100);
  res = res.filter((item) => item.type !== 2);
  res.forEach((item: any) => {
    const i = item;
    const index = s.findIndex((story) => i.id === story.id);
    if (index > -1) {
      i.name = s[index].name;
      i.source = s[index].source || 'tapd';
      i.review_status = i.review_status ?? 0;
      i.checkStatus = i.checkStatus ?? 2;
      i.isMergeToMain = i.isMergeToMain ?? 0;
    }
  });
  return res;

  // const storysDb = await storys.init();
  // const res = storysDb.aggregate([
  //   {
  //     $match: params,
  //   },
  //   {
  //     $lookup: {
  //       from: 'storyWithproject',
  //       localField: 'id',
  //       foreignField: 'id',
  //       as: 'defineField',
  //     },
  //   },
  //   {
  //     $unwind: '$defineField',
  //   },
  //   // {
  //   //   $replaceRoot: {
  //   //     newRoot: { $mergeObjects: [{ name: '$name', source: '$source' }, '$defineField'] },
  //   //   },
  //   // },
  //   {
  //     $project: {
  //       name: 1,
  //       source: 1,
  //       _id: '$defineField._id',
  //       branch: '$defineField.branch',
  //       checkStatus: '$defineField.checkStatus',
  //       developer: '$defineField.developer',
  //       env: '$defineField.env',
  //       http_url_to_repo: '$defineField.http_url_to_repo',
  //       id: '$defineField.id',
  //       isEdit: '$defineField.isEdit',
  //       isMergeToMain: '$defineField.isMergeToMain',
  //       mr: '$defineField.mr',
  //       pid: '$defineField.pid',
  //       project_id: '$defineField.project_id',
  //       project_name: '$defineField.project_name',
  //       review_status: '$defineField.review_status',
  //       unionBranch: '$defineField.unionBranch',
  //     },
  //   },
  // ]);

  // return res.toArray();
};

// 查询获取项目的合并分支
export const syncGetMergeBranch = async (params: { project_name: string; online_time: string }) => {
  const { project_name, online_time } = params;
  const res = await storyWithproject.getList({ project_name, online_time }, undefined, 1, 100);
  return res;
};

// 把开发分支往合并分支里合并
export const syncToMergeBranch = async (params: { develop_branch: string; project_name: string; merge_branch: string }) => {
  const { develop_branch, project_name, merge_branch } = params;
  // 获取合并分支
  // const unionBranch = await storyWithproject.findOne({ project_name, unionBranch: merge_branch });
  // 获取开发分支
  const branch = await storyWithproject.findOne({ project_name, branch: develop_branch });
  // 给开发分支pid赋值成合并分支名称
  // 替换成
  // 给开发分支的pid赋值成合并分支的_id
  if (branch) {
    branch.pid = merge_branch;
    // branch.pid = unionBranch._id;
    // 更新开发分支
    const res = await storyWithproject.update(branch, { project_name, branch: develop_branch });
    return res;
  }
  return new Error('合并失败');
};
// 把开发分支移出合并分支
export const syncOutMergeBranch = async (params: { develop_branch: string; project_name: string }) => {
  const { develop_branch, project_name } = params;

  // 获取开发分支
  const branch = await storyWithproject.findOne({ project_name, branch: develop_branch });
  // 给开发分支pid赋值成合并分支名称
  if (branch) {
    branch.pid = '';
    // 更新开发分支
    const res = await storyWithproject.update(branch, { project_name, branch: develop_branch });
    return res;
  }
  return new Error('移出失败');
};

// 修改状态
export const syncStoryUpdateBranchStatus = async (params: any) => {
  const row = params.selectRows[0];
  const { token } = params;
  const { project_name, unionBranch, isMergeToMain, checkStatus, branch, review_status, _id, name: storyName } = row;
  // 编辑合并分支
  if (unionBranch) {
    const res: any = await storyWithproject.update({ isMergeToMain }, { project_name, unionBranch });
    return res;
  }
  // 编辑开发分支
  let res: any;
  if (!isEmpty(checkStatus)) {
    res = await storyWithproject.update({ checkStatus }, { _id: new ObjectId(_id) });
  }
  if (!isEmpty(review_status)) {
    res = await storyWithproject.update({ review_status }, { _id: new ObjectId(_id) });
  }
  // 日志
  try {
    const info: any = await analysisToken(token);
    if (!isEmpty(review_status)) {
      const rs = reviewStatus.filter((item) => item.value === review_status)[0].label;
      // 代码查验状态
      addLogs(2, 7, info.personName, [storyName, project_name, rs], info.personId);
    }
    if (!isEmpty(checkStatus)) {
      const ck = checkStatusMap.filter((item) => item.value === checkStatus)[0].label;
      // 需求验收状态
      addLogs(2, 1, info.personName, [storyName, project_name, ck], info.personId);
    }
  } catch (err) {
    console.log(err);
  }
  return res;
};

// 接受gitlab mergeTo 主分支的回调
export const syncUpdateBranchToMainStatus = async (params: { user: any; project: any; object_kind: any; object_attributes: any }) => {
  const { user, project, object_kind, object_attributes } = params;
  /** object_attributes.action
   *  open
      close
      reopen
      update
      approved
      unapproved
      approval
      unapproval
      merge
   */
  if (object_kind === 'merge_request' && ['merge', 'close'].includes(object_attributes.action)) {
    const { name } = project as { name: string };
    const { source_branch, target_branch } = object_attributes;
    // 获取一下当前项目的主分支
    const p: any = await projects.getList({ name });
    // 如果存在项目且有主分支等于target_branch。判断是不是往主分支上合并
    if (p && p[0].default_branch === target_branch) {
      const today = dayjs().format('YYYY-MM-DD');
      // 发钉钉通知
      // await sendMsgMergeDone(`${name} 合并完成`, [`合并人：${userName}`, `最后提交人：${String(last_commit.author.name)}`]);
      // 判断发起合并的分支在今日上线项目统计里存不存在，比如手动创建合并分支，没有通过系统创建的也往系统里同步一份
      const res1 = await syncGetList({ online_time: today });
      let flag = false;
      for (let i = 0; i < res1.length; i += 1) {
        // 如果在系统里查到分支名称
        if (res1[i].branch === source_branch || res1[i].unionBranch === source_branch) {
          flag = true;
          break;
        }
      }
      // 如果系统里不存在
      if (!flag) {
        if (object_attributes.action === 'merge') {
          await storyWithproject.insert({ project_name: name, branch: source_branch, unionBranch: source_branch, online_time: today, isMergeToMain: 1, mr: '' });
        } else {
          await storyWithproject.insert({ project_name: name, branch: source_branch, unionBranch: source_branch, online_time: today, isMergeToMain: 3, mr: '' });
        }
      } else if (object_attributes.action === 'merge') {
        await storyWithproject.updateMany({ isMergeToMain: 1, mr: '' }, { project_name: name, $or: [{ unionBranch: source_branch }, { branch: source_branch }] });
      } else if (object_attributes.action === 'close') {
        await storyWithproject.updateMany({ isMergeToMain: 3, mr: '' }, { project_name: name, $or: [{ unionBranch: source_branch }, { branch: source_branch }] });
      }
    }
    let userId = '';
    const i = object_attributes.title.indexOf('batchId');
    if (i !== -1) {
      userId = object_attributes.title.substr(i).split(':')[1] || '';
    }

    // 加日志
    try {
      if (object_attributes.action === 'close') {
        addLogs(2, 12, user.name, [user.name, name], userId);
      } else if (object_attributes.action === 'merge') {
        addLogs(2, 9, user.name, [user.name, name], userId);
      }
    } catch (err) {
      console.log(err);
    }
  }
};

export const sendOnlineStoryMsg = async (params) => {
  const s: any = await syncStorySearch(params);
  const dayjs_copy: any = dayjs();
  // 2是星期三
  const tamps = new Date(dayjs_copy.weekday(2).format('YYYY-MM-DD')).getTime();
  if (s.total > 0) {
    // sendMsgMergeDone('周三上线需求通知', [`周三有${s.total as string}个需求上线，请及时关注`, `访问链接：http://59.110.10.239:8083/onlineStory?time=${tamps}`]);
    ddSendOnlineStoryMsg('周三上线需求通知', [`周三有${s.total as string}个需求上线，请及时关注`, `访问链接：http://59.110.10.239:8083/onlineStory?time=${tamps}`]);
  }
  return s;
};
